<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="effect-container">
    <canvas id="cloudCanvas" class="cloud-canvas"></canvas>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted } from 'vue';

onMounted(() => {
  const canvas = document.getElementById('cloudCanvas') as HTMLCanvasElement;
  const ctx = canvas.getContext('2d')!;
  let particles: Particle[] = [];
  let hue = 0;

  // 初始化Canvas尺寸
  const resizeCanvas = () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  };
  resizeCanvas();
  window.addEventListener('resize', resizeCanvas);

  // 粒子类定义
  class Particle {
    x: number;
    y: number;
    size: number;
    speedX: number;
    speedY: number;
    color: string;
    alpha: number;

    constructor(mouseX: number, mouseY: number) {
      this.x = mouseX;
      this.y = mouseY;
      this.size = Math.random() * 8 + 2; // 2-10px随机大小
      this.speedX = (Math.random() - 0.5) * 2; // -1~1随机水平速度
      this.speedY = (Math.random() - 0.5) * 2; // -1~1随机垂直速度
      this.alpha = 1; // 初始不透明
      this.color = `hsl(${hue}, 100%, 50%)`; // HSL颜色模式
    }

    // 更新粒子状态
    update() {
      this.x += this.speedX;
      this.y += this.speedY;
      this.size *= 0.97; // 逐渐缩小
      this.alpha *= 0.95; // 逐渐透明
    }

    // 绘制粒子（优化模糊效果）
    draw() {
      ctx.save();
      ctx.globalAlpha = this.alpha;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      ctx.fillStyle = this.color;
      // 仅对较大的粒子应用模糊（减少计算量）
      if (this.size > 3) ctx.filter = 'blur(1px)';
      else ctx.filter = 'none';
      ctx.fill();
      ctx.restore();
    }
  }

  // 鼠标移动事件处理（添加节流）
  let isThrottling = false;
  const handleMouseMove = (e: MouseEvent) => {
    if (!isThrottling) {
      hue = (hue + 3) % 360;
      if (particles.length < 200) {
        for (let i = 0; i < 3; i++) {
          particles.push(new Particle(e.clientX, e.clientY));
        }
      }
      isThrottling = true;
      setTimeout(() => { isThrottling = false; }, 50); // 每50ms最多触发一次
    }
  };
  window.addEventListener('mousemove', handleMouseMove);

  // 动画循环
  const animate = () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 提前清理更小/更透明的粒子（原条件：size>0.2 & alpha>0.05）
    particles = particles.filter(p => p.size > 0.5 && p.alpha > 0.1);
    particles.forEach(p => {
      p.update();
      p.draw();
    });
    requestAnimationFrame(animate);
  };
  animate();

  // 卸载时清理事件监听
  onUnmounted(() => {
    window.removeEventListener('resize', resizeCanvas);
    window.removeEventListener('mousemove', handleMouseMove);
  });
});
</script>

<style scoped>
.effect-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  pointer-events: none; /* 不影响下层交互 */
}

.cloud-canvas {
  width: 100%;
  height: 100%;
}
</style>
